#import "NearbyMerchantUI.h"
#import "PullingRefreshTableView.h"
#import "yedianxiangqingViewController.h"
@interface NearbyMerchantUI () <
PullingRefreshTableViewDelegate,
UITableViewDataSource,
UITableViewDelegate
>
@property (retain,nonatomic) PullingRefreshTableView *tableView;
@property (retain,nonatomic) NSMutableArray *list;
@property (nonatomic) BOOL refreshing;
@property (assign,nonatomic) NSInteger page;

@end

@implementation NearbyMerchantUI
@synthesize tableView = _tableView;
@synthesize list = _list;
@synthesize refreshing = _refreshing;
@synthesize page = _page;
@synthesize pageSize,allCnt,job_type,locationManager;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row=[indexPath row];
    NSDictionary *dic=[self.list objectAtIndex:row];
    NSString* merchant_id=[dic objectForKey:@"merchant_id"];
    yedianxiangqingViewController* ui=[[yedianxiangqingViewController alloc] init];
    ui.title = @"夜店详情";
    ui.merchantId=[merchant_id intValue];
    [self.navigationController pushViewController:ui animated:NO];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 87.0 ;
}

- (void)loadView
{
    [super loadView];
    _list = [[NSMutableArray alloc] init ];
    CGRect frame;
    float iosVersion=[[[UIDevice currentDevice] systemVersion] floatValue];
    
    int h=[Tools getScreenHeight];
    
    
    
    _tableView = [[PullingRefreshTableView alloc] initWithFrame:CGRectMake(0, 44, 320, h-44-65) pullingDelegate:self];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    [self.view addSubview:_tableView];
    
}
-(void)jbFn{
    job_type=1;
    self.refreshing=YES;
    [self.list removeAllObjects];
    [self loadData];
    UIImage* jb=[UIImage imageNamed:@"left_focus"];
    
    UIImage* ktv=[UIImage imageNamed:@"right"];
    
    
    
    NSArray* jbArray=[distanceBtn subviews];
    for(UIView* v in jbArray){
        if ([v isKindOfClass:[UILabel class]]) {
            [v removeFromSuperview];
        }
    }
    [distanceBtn setBackgroundImage:jb forState:0];
    UILabel* jbLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320/3, 44)];
    jbLb.text=@"时间";
    jbLb.textAlignment=NSTextAlignmentCenter;
    jbLb.textColor=[UIColor whiteColor];
    jbLb.backgroundColor=[UIColor clearColor];
    [distanceBtn addSubview:jbLb];
    /////
    NSArray* ktvArray=[ktvBtn subviews];
    for(UIView* v in ktvArray){
        if ([v isKindOfClass:[UILabel class]]) {
            [v removeFromSuperview];
        }
    }
    [ktvBtn setBackgroundImage:ktv forState:0];
    
    UILabel*  ktvLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320/3, 44)];
    ktvLb.text=@"距离";
    ktvLb.textAlignment=NSTextAlignmentCenter;
    ktvLb.textColor=[UIColor darkGrayColor];
    ktvLb.backgroundColor=[UIColor clearColor];
    [ktvBtn addSubview:ktvLb];
    
    
    
    
    
    
    
}

-(void)ktvFn{
    job_type=2;
    self.refreshing=YES;
    [self.list removeAllObjects];
    [self loadData];
    UIImage* jb=[UIImage imageNamed:@"left"];
    
    UIImage* ktv=[UIImage imageNamed:@"right_focus"];
    
    NSArray* jbArray=[distanceBtn subviews];
    for(UIView* v in jbArray){
        if ([v isKindOfClass:[UILabel class]]) {
            [v removeFromSuperview];
        }
    }
    [distanceBtn setBackgroundImage:jb forState:0];
    UILabel* jbLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320/3, 44)];
    jbLb.text=@"时间";
    jbLb.textAlignment=NSTextAlignmentCenter;
    jbLb.textColor=[UIColor darkGrayColor];
    jbLb.backgroundColor=[UIColor clearColor];
    [distanceBtn addSubview:jbLb];
    /////
    NSArray* ktvArray=[ktvBtn subviews];
    for(UIView* v in ktvArray){
        if ([v isKindOfClass:[UILabel class]]) {
            [v removeFromSuperview];
        }
    }
    [ktvBtn setBackgroundImage:ktv forState:0];
    
    UILabel*  ktvLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320/3, 44)];
    ktvLb.text=@"距离";
    ktvLb.textAlignment=NSTextAlignmentCenter;
    ktvLb.textColor=[UIColor whiteColor];
    ktvLb.backgroundColor=[UIColor clearColor];
    [ktvBtn addSubview:ktvLb];
    //
    
    
    
    
    
}

-(void)publishFn{
    PublishActivityUI* ui=[[PublishActivityUI alloc] init];
    [self.navigationController pushViewController:ui animated:NO];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.pageSize=10;
    job_type=1;
    self.page=0;
    
    self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 110, 0);
    self.view.backgroundColor=[UIColor whiteColor];
    
    UIImage *headImg=[UIImage imageNamed:@"navigation.png"];
    headImg=[Tools resizeImageToSize:headImg toSize:CGSizeMake(320, 44)];
    UINavigationBar *navBar = self.navigationController.navigationBar;
#define kSCNavBarImageTag 10
    if ([navBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
    {
        [navBar setBackgroundImage:headImg forBarMetrics:UIBarMetricsDefault];
    }
    else
    {
        UIImageView *imageView = (UIImageView *)[navBar viewWithTag:kSCNavBarImageTag];
        if (imageView == nil)
        {
            imageView = [[UIImageView alloc] initWithImage:
                         headImg];
            [imageView setTag:kSCNavBarImageTag];
            [navBar insertSubview:imageView atIndex:0];
            //[imageView release];
            
        }
    }
    flag=1;
    
    UILabel* titleLb=[[UILabel alloc] initWithFrame:CGRectMake(120, 0, 80, 40)];
    titleLb.text=@"附近夜店";
    titleLb.font = [UIFont systemFontOfSize:HEAD_SIZE];
    titleLb.textColor=[UIColor whiteColor];
    titleLb.textAlignment=NSTextAlignmentCenter;
    titleLb.backgroundColor=[UIColor clearColor];
    self.navigationItem.titleView=titleLb;
    
    
    UIButton* cancelBtn= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
    [cancelBtn addTarget:self action:@selector(clickOnBackBut) forControlEvents:UIControlEventTouchUpInside];
    CGRect frame_1= CGRectMake(0,12, 20,20);
    UIImageView*  backView=[[UIImageView alloc] initWithFrame:frame_1];
    UIImage* image= [UIImage imageNamed:@"back2016"];
    backView.image=image;
    [cancelBtn addSubview:backView];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:cancelBtn];
    
    
    UIButton* publishBtn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0,60, 44)];
    [publishBtn addTarget:self action:@selector(publishFn) forControlEvents:UIControlEventTouchUpInside];
    UILabel* publishLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 7, 60, 30)];
    publishLb.text=@"发布";
    publishLb.textColor=[UIColor whiteColor];
    [publishBtn addSubview:publishLb];
    //self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:publishBtn];
    
    
    
    UIImage* left_focus=[UIImage imageNamed:@"left_focus"];
    
    UIImage* right=[UIImage imageNamed:@"right"];
    
    
    
    distanceBtn=[[UIButton alloc] initWithFrame:CGRectMake(1, 0, 320/2, 44)];
    [distanceBtn setBackgroundImage:left_focus forState:0];
    [distanceBtn addTarget:self action:@selector(jbFn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:distanceBtn];
    UILabel* jbLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320/3, 44)];
    jbLb.text=@"距离";
    jbLb.textAlignment=NSTextAlignmentCenter;
    jbLb.textColor=[UIColor whiteColor];
    jbLb.backgroundColor=[UIColor clearColor];
    [distanceBtn addSubview:jbLb];
    //
    ktvBtn=[[UIButton alloc] initWithFrame:CGRectMake(320/2+1, 0, 320/2, 44)];
    [ktvBtn setBackgroundImage:right forState:0];
    [ktvBtn addTarget:self action:@selector(ktvFn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:ktvBtn];
    
    UILabel*  ktvLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320/2, 44)];
    ktvLb.text=@"时间";
    ktvLb.textAlignment=NSTextAlignmentCenter;
    ktvLb.textColor=[UIColor darkGrayColor];
    ktvLb.backgroundColor=[UIColor clearColor];
    [ktvBtn addSubview:ktvLb];
    
    
    
    self.locationManager = [[CLLocationManager alloc] init];
    
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100.0f;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        NSLog(@"requestAlwaysAuthorization....");
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager startUpdatingLocation];
    }else{
        [self.locationManager startUpdatingLocation];
    }
    
    
    
    
    [self.tableView setBackgroundView:nil];
    
    flag=1;
    self.page=0;
    [NSThread detachNewThreadSelector:@selector(loadData) toTarget:self withObject:nil];
    
    
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // 获取经纬度
    NSLog(@"纬度:%f",newLocation.coordinate.latitude);
    NSLog(@"经度:%f",newLocation.coordinate.longitude);
    // 停止位置更新
    [manager stopUpdatingLocation];
    longitude=newLocation.coordinate.longitude;
    latitude=newLocation.coordinate.latitude;
    
    
}

// 定位失误时触发
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"error:%@",error);
}
-(void)clickOnBackBut{
    [self.navigationController popViewControllerAnimated:NO];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)loadData{
    
    if (self.refreshing) {
        self.page = 0;
        self.refreshing = NO;
        [self.list removeAllObjects];
    }
  
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString*  longitudeStr=[ud objectForKey:@"longitude"];
    NSString*  latitudeStr=[ud objectForKey:@"latitude"];
    
    
    NSString *url=@"";
    url=[HOST stringByAppendingString:@"index.php/AppNearby/getNearByMerchantList?currentPage="];
    NSMutableString *mUrl=[[NSMutableString alloc] initWithString:url];
    NSString  *sCurrentPage=[NSString stringWithFormat:@"%d",self.page];
    [mUrl appendString:sCurrentPage];
    [mUrl appendString:@"&longi="];
    
    [mUrl appendString:[NSString stringWithFormat:@"%@",longitudeStr]];
    //
    [mUrl appendString:@"&lanti="];
    
    [mUrl appendString:[NSString stringWithFormat:@"%@",latitudeStr]];
    
    
    
    
    NSLog(@"murl===%@",mUrl);
    
    
    NSError *error;
    NSString *jsonStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:mUrl] encoding:NSUTF8StringEncoding error:&error];
    NSLog(@"jsonStr===%@",jsonStr);
    
    NSDictionary* tmpDic=[NSDictionary dictionaryWithDictionary:[jsonStr JSONValue]];
    
    NSString* _allCnt=[tmpDic objectForKey:@"size"];
    self.allCnt=[_allCnt intValue];
    NSMutableArray *infoList=[tmpDic objectForKey:@"list"];
    
    for(int i = 0 ; i< [infoList count];i++){
        [self.list addObject: [infoList objectAtIndex:i]];
    }
    self.page++;
    [self performSelectorOnMainThread:@selector(didFinishRequest) withObject:nil waitUntilDone:YES];
    
    
    
}
-(void)didFinishRequest{
    NSLog(@"%d====",self.list.count);
    if (self.list.count>=self.allCnt) {
        
        
        
        if (self.allCnt<=self.pageSize) {
            [self.tableView tableViewDidFinishedLoading];
            self.tableView.reachedTheEnd  = YES;
            [self.tableView reloadData];
        }
        if (self.allCnt==self.list.count) {
            [self.tableView tableViewDidFinishedLoading];
            self.tableView.reachedTheEnd  = YES;
            [self.tableView reloadData];
        }
        self.tableView.reachedTheEnd  = YES;
        
    } else {
        [self.tableView tableViewDidFinishedLoading];
        self.tableView.reachedTheEnd  = NO;
        [self.tableView reloadData];
    }
    
}

#pragma mark - TableView*
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.list count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"_CELL";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] ;
    }
    NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
    for (UIView *subview in subviews) {
        if ([subview isKindOfClass:[UILabel class]]) {
            [subview removeFromSuperview];
        }
        if ([subview isKindOfClass:[UIButton class]]) {
            [subview removeFromSuperview];
        }
        if ([subview isKindOfClass:[UIImageView class]]) {
            [subview removeFromSuperview];
        }
        
    }
    
    NSUInteger row=indexPath.row;
    if (row<self.list.count) {
        NSDictionary* dic=[self.list objectAtIndex:row];
        UIImageView* avatarImgView=[[UIImageView alloc] initWithFrame:CGRectMake(4+2,4+2, 68-4, 80-4-4)];
        NSString* avatar=[dic objectForKey:@"logo"];
        avatar=[NSString stringWithFormat:@"%@",avatar];
        if (avatar!=nil&&[avatar length]>5) {
            
            if (avatar && [avatar rangeOfString:@"http"].location != NSNotFound) {
                [avatarImgView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",avatar]] placeholderImage:[UIImage new]];
            }else{
                avatar=[HOST stringByAppendingString:avatar];
                NSLog(@"用户头像=%@",avatar);
                NSURL* avatarURL=[NSURL URLWithString:avatar];
                [avatarImgView setImageWithURL:avatarURL placeholderImage:[UIImage imageNamed:@"empty_photo"]];
            }
            [cell.contentView addSubview:avatarImgView];
            
//            avatar=[HOST stringByAppendingString:avatar];
//            NSLog(@"司机头像=%@",avatar);
//            NSURL* avatarURL=[NSURL URLWithString:avatar];
//            [avatarImgView setImageWithURL:avatarURL placeholderImage:[UIImage imageNamed:@"empty_photo"]];
//            [cell.contentView addSubview:avatarImgView];
        }else{
            avatarImgView.image=[UIImage imageNamed:@"empty_photo"];
            [cell.contentView addSubview:avatarImgView];
        }
        
        
        int x=15;
        //标题
        NSString* name=[dic objectForKey:@"name"];
        name=[NSString stringWithFormat:@"%@",name];
        UILabel* titleLB=[[UILabel alloc] initWithFrame:CGRectMake(68+x/2, 6, 240, 22)];
        
        titleLB.text=name;
        titleLB.font=[UIFont boldSystemFontOfSize:14];
        titleLB.textColor=[UIColor blackColor];
        titleLB.backgroundColor=[UIColor clearColor];
        [cell.contentView addSubview:titleLB];
        
        //////////////////
        NSString* address=[dic objectForKey:@"qm"];
        address=[NSString stringWithFormat:@"%@",address];
        UILabel* addressLB=[[UILabel alloc] initWithFrame:CGRectMake(68+x/2,40, 120, 22)];
        addressLB.text=address;
        
        
        
        addressLB.font=[UIFont systemFontOfSize:12];
        addressLB.textColor=[UIColor darkGrayColor];
        addressLB.backgroundColor=[UIColor clearColor];
        [cell.contentView addSubview:addressLB];
        ////////
        
        
        //
        
        NSString* juli=[dic objectForKey:@"juli"];
        UILabel* juliLB=[[UILabel alloc] initWithFrame:CGRectMake(x+68+150, 22,70, 22)];
        
        juliLB.text=[NSString stringWithFormat:@"%@",juli];
        juliLB.font=[UIFont systemFontOfSize:12];
        juliLB.textColor=[UIColor grayColor];
        juliLB.textAlignment=NSTextAlignmentRight;
        
        
        juliLB.backgroundColor=[UIColor clearColor];
        [cell.contentView addSubview:juliLB];
        
        
        ////
        
        
        
        
        UIImage* arrowImg=[UIImage imageNamed:@"arrow"];
        UIImageView*  arrowImgView=[[UIImageView alloc] initWithFrame:CGRectMake(290, 40, 12*0.9, 21*0.9)];
        arrowImgView.image=arrowImg;
        [cell.contentView addSubview:arrowImgView];
        
        
        //        UIImage* henxian=[UIImage imageNamed:@"凹线条640.png"];
        //        UIImageView *henxianView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 1)];
        //        henxianView.image=henxian;
        //        [cell.contentView addSubview:henxianView];
        
        
        
    }
    
    return cell;
}

#pragma mark - PullingRefreshTableViewDelegate
- (void)pullingTableViewDidStartRefreshing:(PullingRefreshTableView *)tableView{
    self.refreshing = YES;
    [self performSelector:@selector(loadData) withObject:nil afterDelay:0.1];
}

- (NSDate *)pullingTableViewRefreshingFinishedDate{
    NSDateFormatter *df = [[NSDateFormatter alloc] init ];
    df.dateFormat = @"yyyy-MM-dd HH:mm";
    NSData * date = [NSDate date];//获取当前的时间
    NSString *MyHitOrderListUIStr= [df stringFromDate:date];
    date = [df dateFromString:MyHitOrderListUIStr];
    return date;
}

- (void)pullingTableViewDidStartLoading:(PullingRefreshTableView *)tableView{
    [self performSelector:@selector(loadData) withObject:nil afterDelay:0.1f];
}

#pragma mark - Scroll

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.tableView tableViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self.tableView tableViewDidEndDragging:scrollView];
}

@end
